"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _configContext = require("../../../../extends/configContext");

var _utils = require("./utils");

var _injectValue = require("../../../../utils/inject-value");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var Circle = function Circle(_ref) {
  var _ref$style = _ref.style,
      style = _ref$style === void 0 ? {} : _ref$style,
      _ref$percent = _ref.percent,
      percent = _ref$percent === void 0 ? 0 : _ref$percent,
      _ref$theme = _ref.theme,
      theme = _ref$theme === void 0 ? 'default' : _ref$theme,
      _ref$lineWidth = _ref.lineWidth,
      lineWidth = _ref$lineWidth === void 0 ? 2 : _ref$lineWidth,
      _ref$width = _ref.width,
      width = _ref$width === void 0 ? 160 : _ref$width,
      _ref$className = _ref.className,
      className = _ref$className === void 0 ? '' : _ref$className,
      _ref$text = _ref.text,
      text = _ref$text === void 0 ? '' : _ref$text,
      _ref$isShowText = _ref.isShowText,
      isShowText = _ref$isShowText === void 0 ? true : _ref$isShowText,
      _ref$tips = _ref.tips,
      tips = _ref$tips === void 0 ? '' : _ref$tips,
      children = _ref.children,
      _ref$lineCap = _ref.lineCap,
      lineCap = _ref$lineCap === void 0 ? 'butt' : _ref$lineCap;

  var _useConfig = (0, _configContext.useConfig)(),
      clsPrefix = _useConfig.clsPrefix;

  var _useState = (0, _react.useState)({
    canvas: null,
    ctx: null,
    width: 0,
    height: 0
  }),
      _useState2 = _slicedToArray(_useState, 2),
      canvasInfo = _useState2[0],
      setCanvasInfo = _useState2[1]; // 以随机数，定义视图id，避免id重复


  var canvasId = (0, _react.useRef)(null);
  var wrapperId = (0, _react.useRef)(null);
  (0, _react.useEffect)(function () {
    initCanvas();
  }, []);
  (0, _react.useEffect)(function () {
    var ctx = canvasInfo.ctx;

    if (ctx) {
      drawRound();
    }
  }, [percent, canvasInfo]);

  var initCanvas = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var canvas, ctx, _wrapperId$current$ge, width, height, dpr;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              canvas = canvasId.current;
              ctx = canvasId.current.getContext('2d');
              _wrapperId$current$ge = wrapperId.current.getBoundingClientRect(), width = _wrapperId$current$ge.width, height = _wrapperId$current$ge.height;
              dpr = 3;
              canvas.width = width * dpr;
              canvas.height = height * dpr;
              ctx.scale(dpr, dpr);
              setCanvasInfo({
                canvas: canvas,
                ctx: ctx,
                width: width,
                height: height
              });

            case 8:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function initCanvas() {
      return _ref2.apply(this, arguments);
    };
  }();

  var getCircle = function getCircle() {
    var width = canvasInfo.width,
        height = canvasInfo.height;
    var radius = (0, _utils.toFixed)(0.5 * Math.min(width, height));

    if (radius > lineWidth) {
      radius -= lineWidth;
    }

    var range = 2 * (percent / 100) * Math.PI;
    var offsetRadian = -0.5 * Math.PI;
    return {
      radius: radius,
      range: range,
      offsetRadian: offsetRadian
    };
  };

  var drawRound = function drawRound() {
    var ctx = canvasInfo.ctx,
        height = canvasInfo.height,
        width = canvasInfo.width;

    var _getCircle = getCircle(),
        radius = _getCircle.radius,
        range = _getCircle.range,
        offsetRadian = _getCircle.offsetRadian; // 绘制前先清除，以防被原有图案影响


    ctx.clearRect(0, 0, width, height);
    ctx.lineWidth = lineWidth;
    ctx.lineCap = lineCap;
    ctx.beginPath();
    ctx.strokeStyle = '#F6F7F9';
    ctx.arc((0, _utils.toFixed)(width / 2), (0, _utils.toFixed)(height / 2), radius, 0, 2 * Math.PI);
    ctx.stroke();

    if (range === 0) {
      return;
    }

    ctx.beginPath();
    ctx.strokeStyle = getColor();
    ctx.arc((0, _utils.toFixed)(width / 2), (0, _utils.toFixed)(height / 2), radius, offsetRadian, range + offsetRadian);
    ctx.stroke();
  };

  var getColor = function getColor() {
    if (theme === 'default') {
      return '#FEC32D';
    }

    if (theme === 'success') {
      return '#57BD6A';
    }

    if (theme === 'danger') {
      return '#E54545';
    }

    return '#FEC32D';
  };

  return /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-progress-circle")
  }, /*#__PURE__*/_react.default.createElement("div", {
    ref: wrapperId,
    className: "".concat(clsPrefix, "-progress-circle__area ").concat(className),
    style: style
  }, /*#__PURE__*/_react.default.createElement("canvas", {
    ref: canvasId,
    className: "".concat(clsPrefix, "-progress-circle__canvas")
  }), !children && isShowText && /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-progress-circle__current-text"),
    id: "progress-num"
  }, text ? /*#__PURE__*/_react.default.createElement("span", {
    className: "text--chinese"
  }, (0, _injectValue.injectValue)(text)(percent)) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, percent, /*#__PURE__*/_react.default.createElement("span", {
    className: "text--symbol"
  }, "%"))), children && /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-progress-circle__children")
  }, children)), /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-progress-circle__tips")
  }, tips));
};

var _default = Circle;
exports.default = _default;